package com.ltmonitor.server.netty;

import java.util.List;

import com.ltmonitor.jt808.protocol.T808Message;
import com.ltmonitor.server.mina.JT808TransferQueue;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 * 808协议解析器，专用于nettry server
 * 
 */
public class ProtocolDecoder extends ByteToMessageDecoder {
	private static final int MIN_HEADER_SIZE = 10;

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in,
			List<Object> out) throws Exception {
		if (in == null) {
			return;
		}

		in.markReaderIndex();
		// this.logger.warn(Tools.ToHexString(data));
		// int pos = 0;
		while (in.isReadable()) {
			in.markReaderIndex();
			int packetBeginIndex = in.readerIndex();
			byte tag = in.readByte();
			// 搜索包的开始位置
			if (tag == 0x7E && in.isReadable()) {
				tag = in.readByte();
				// 防止是两个0x7E,取后面的为包的开始位置
				// 寻找包的结束
				while (tag != 0x7E) {
					if (in.isReadable() == false) {
						in.resetReaderIndex(); // 没有找到结束包，等待下一次包
						// logger.error("半包:"+Tools.ToHexString(data));
						return;
					}
					tag = in.readByte();
				}
				int pos = in.readerIndex();
				int packetLength = pos - packetBeginIndex;
				if (packetLength > 1) {
					byte[] tmp = new byte[packetLength];
					in.resetReaderIndex();
					in.readBytes(tmp);
					T808Message message = new T808Message();
					message.ReadFromBytes(tmp);
					JT808TransferQueue.forward(message.getSimNo(), tmp); // 808转发
					out.add(message); // 触发接收Message的事件
					// return message;
				} else {
					// 说明是两个0x7E
					in.resetReaderIndex();
					in.readByte(); // 两个7E说明前面是包尾，后面是包头
				}
			}
		}

		return;
	}


}
